package com.ling.minio.service;

import io.minio.GetBucketPolicyArgs;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.credentials.AssumeRoleProvider;
import io.minio.credentials.Credentials;
import io.minio.errors.MinioException;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Value;

import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

public class MinioService {

    private final MinioClient minioClient;

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.access-key}")
    private String accessKey;

    @Value("${minio.access-secret}")
    private String secretKey;

    @Value("${minio.bucket}")
    private String bucket;

    // 构造方法初始化 MinIO 客户端
    public MinioService() {
        this.minioClient = MinioClient.builder()
                .endpoint("http://127.0.0.1:9090")  // MinIO服务的URL
                .credentials("Mjnq571WYXaOpikYDBKm", "82Cgtyb6YTZB6I8OQPXHTP31vlJnKOKCipOLpeQP")  // MinIO访问凭证
                .build();
    }

    // 生成下载文件的预签名 URL
    public String generatePresignedDownloadUrl(String bucketName, String objectName) throws Exception {
        try {
            GetPresignedObjectUrlArgs getPresignedObjectUrlArgs = GetPresignedObjectUrlArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .method(Method.GET)
                    //.expiry(60) // 单位秒
                    .expiry(24 * 3600 * 7, TimeUnit.SECONDS)
                    .build();
            return minioClient.getPresignedObjectUrl(getPresignedObjectUrlArgs);
            // 使用预签名URL生成下载文件的链接
//            return minioClient.getPresignedObjectUrl(
//                    // 方法为GET请求，用于下载
//                    Method.GET,
//                    bucketName,
//                    objectName,
//                    expiryDurationMinutes,  // 设置有效期，单位为分钟
//                    null  // 额外的请求参数（如有需要可添加）
//            );
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Failed to generate presigned download URL", e);
        }
    }

    // 生成上传文件的预签名 URL（带有时效性）
// 生成预签名的 PUT URL（上传文件）
    public String generatePresignedPutUrl(String bucketName, String objectName) throws Exception {
        // 生成预签名的 PUT 请求 URL，有效期为 1 小时
        GetPresignedObjectUrlArgs getPresignedObjectUrlArgs = GetPresignedObjectUrlArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .method(Method.PUT)
                //.expiry(60) // 单位秒
                .expiry(24 * 3600 * 7, TimeUnit.SECONDS)
                .build();
        return minioClient.getPresignedObjectUrl(getPresignedObjectUrlArgs);
    }


    public Credentials getCredentials() {
        try {
            AssumeRoleProvider roleProvider = new AssumeRoleProvider(
                    "http://127.0.0.1:9090",
                    "OgfUdJ79KaHn5VD1rNCI",
                    "CgI64ITuXpKNIFjfKEdTH1MXniflaNq5zmuY4RLQ",
                    3600,
                    getBucketPolicy(),
                    null,
                    null,
                    "",
                    null,
                    null
            );
            return roleProvider.fetch();
        } catch (NoSuchAlgorithmException e) {
            e.getMessage();

        }

        return null;
    }

    public String getBucketPolicy() {
        try {
            return minioClient.getBucketPolicy(GetBucketPolicyArgs.builder().bucket("minio-upload").build());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    //STS方式生成临时凭据

    public static void main(String[] args) throws Exception {
        MinioService minioService = new MinioService();

        // 生成预签名下载URL
//        String downloadUrl = minioService.generatePresignedDownloadUrl("minio-upload", "R-C.jpg");
//
//        System.out.println("Download URL: " + downloadUrl);

        //获取上传文件的预签名URL
//        String uploadUrl = minioService.generatePresignedPutUrl("minio-upload", "600.jpg");
//        System.out.println("Upload URL: " + uploadUrl);

        // 获取临时访问凭证
        Credentials credentials = minioService.getCredentials();
        System.out.println("Access Key: " + credentials.accessKey());
        System.out.println("Secret Key: " + credentials.secretKey());
        System.out.println("Session Token: " + credentials.sessionToken());

        //获取桶策略
//        String bucketPolicy = minioService.getBucketPolicy();
//        System.out.println(bucketPolicy);

    }
}
